import java.io.ByteArrayInputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import lejos.nxt.LCD;

public class ReceivedMessage {
	private int move;
	private int rotate;
	private int numScans;
	private boolean reboot;
	private int drive = -10;
	private int turn = -10;
	
	
	public ReceivedMessage(String xmlstring) {
		XMLInputFactory inputfactory = XMLInputFactory.newInstance();
		try {
			LCD.clear();
			XMLStreamReader xmlreader = inputfactory.createXMLStreamReader(new ByteArrayInputStream(xmlstring.getBytes()));
			while (xmlreader.hasNext()){
				if (xmlreader.getEventType() == XMLStreamConstants.START_ELEMENT || 
						xmlreader.getEventType() == XMLStreamConstants.ATTRIBUTE) {			
					if (xmlreader.getName().toString().equals("move"))
						move = Integer.parseInt(xmlreader.getAttributeValue(0));
					else if (xmlreader.getName().toString().equals("rotate"))
						rotate = Integer.parseInt(xmlreader.getAttributeValue(0));
					else if (xmlreader.getName().toString().equals("G4Drive"))
						drive = Integer.parseInt(xmlreader.getAttributeValue(0));
					else if (xmlreader.getName().toString().equals("G4Turn"))
						turn = Integer.parseInt(xmlreader.getAttributeValue(0));
					else if (xmlreader.getName().toString().equals("scan"))
						numScans = Integer.parseInt(xmlreader.getAttributeValue(0));
					else if (xmlreader.getName().toString().equals("reboot"))
						reboot = true;
					else
						;
					xmlreader.next();
					
				} else {
					xmlreader.next();
				}
					//System.out.println(xmlreader.getName().toString());
			
			}		
		
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}	
	}

	public int getMove() {
		return move;
	}
	
	public int getRotate() {
		return rotate;
	}

	public int getTurn() {
		return turn;
	}
	
	public int getDrive() {
		return drive;
	}
	
	public int getNumScans() {
		return numScans;
	}
	
	public String toString() {
	    StringBuilder result = new StringBuilder();
	    //result.append(this.getClass().getName() + ":  ");
	    if (reboot) {
	    	result.append("REBOOT\n");
	    }
	    result.append("Drive " + Math.abs(move) + "cm");
	    if (move >= 0)
	    	result.append("forwards. ");
	    else
	    	result.append("backwards. ");
	    result.append("Turn " + Math.abs(rotate) + "degrees");
	    if (rotate >= 0)
	    	result.append("clockwise.");
	    else
	    	result.append("anti-clockwise.");
	    result.append("Scan " + numScans + "times.");
	    
	    return result.toString();
	}
}
